package com.audaque.jadmin.system.shiro;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import com.alibaba.fastjson.JSON;
import com.audaque.jadmin.common.model.MessageModel;
import com.audaque.jadmin.common.utils.WebUtils;

/**
 * @Description :
 * @FileName: PermissionFilter.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年10月19日 下午2:20:28
 * @Version:V1.00
 */
public class PermissionFilter extends AccessControlFilter {

	private static final Logger LOG = Logger.getLogger(PermissionFilter.class);

	/**
	 * 配置几个不需要权限的页面，比如：登录页、首页等等，没权限时，按需跳转
	 */
	private String indexUrl;

	public String getIndexUrl() {
		return indexUrl;
	}

	public void setIndexUrl(String indexUrl) {
		this.indexUrl = indexUrl;
	}

	/**
	 * isAccessAllowed：表示是否允许访问；mappedValue就是[urls]配置中拦截器参数部分，如果允许访问返回true，
	 * 否则false
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		String pers[] = (String[]) mappedValue;
		if (pers == null || pers.length <= 0) {
			return true;
		}
		Subject subject = SecurityUtils.getSubject();

		boolean permittedAll = true;

		for (String ps : pers) {
			String[] parray = ps.split("-");
			boolean isPermitted = false;
			for (String s : parray) {
				System.out.println("链接: " + s);
				isPermitted = isPermitted || subject.isPermitted(s);
			}
			permittedAll = permittedAll && isPermitted;
		}
		if (permittedAll) {
			return true;
		}
		return false;
	}

	/**
	 * onAccessDenied：表示当访问拒绝时是否已经处理了；如果返回true表示需要继续处理；如果返回false表示该拦截器实例已经处理了，
	 * 将直接返回即可。
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String basePath = WebUtils.getBasePath();
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		LOG.info("请求的链接： " + httpRequest.getRequestURI());

		boolean isAjax = WebUtils.isAjaxRequest(httpRequest);
		if (isAjax) {
			httpResponse.setCharacterEncoding("UTF-8");
			PrintWriter writer = httpResponse.getWriter();
			MessageModel model = new MessageModel(false, "您没有操作权限");
			writer.write(JSON.toJSONString(model));
			return false;
		}
		httpResponse.sendRedirect(basePath + getLoginUrl());
		return false;
	}
}
